package com.css.prompt.service;

import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.css.prompt.model.MyPrompt;
import com.css.prompt.repository.MyPromptRepository;

@Service
public class MyPromptService {

    private final MyPromptRepository repository;

    public MyPromptService(MyPromptRepository repository) {
        this.repository = repository;
    }

    public List<MyPrompt> getAll() {
        return repository.findAll();
    }

    public Optional<MyPrompt> getById(Long id) {
        return repository.findById(id);
    }

    public MyPrompt save(MyPrompt prompt) {
    	prompt.setDate(LocalDate.now());
        return repository.save(prompt);
    }

    public MyPrompt update(Long id, MyPrompt updated) {
        return repository.findById(id).map(existing -> {
            existing.setTitle(updated.getTitle());
            existing.setDescription(updated.getDescription());
            existing.setContent(updated.getContent());
            existing.setCategory(updated.getCategory());
            existing.setFolder(updated.getFolder());
            existing.setDate(updated.getDate());
            existing.setAuthor(updated.getAuthor());
            existing.setEmail(updated.getEmail());
            existing.setTags(updated.getTags());
            existing.setVersion(updated.getVersion());
            existing.setRoleName(updated.getRoleName());
            existing.setBase(updated.getBase());
            existing.setReusePrefix(updated.getReusePrefix());
            existing.setSelenium(updated.getSelenium());
            existing.setPlaywright(updated.getPlaywright());
            existing.setBoth(updated.getBoth());
            
            return repository.save(existing);
        }).orElseThrow(() -> new RuntimeException("Prompt not found"));
    }

    @Transactional
    public void deletePrompt(Long id) {
        // 1. 获取将要删除的 prompt
        MyPrompt promptToDelete = repository.findById(id).orElseThrow(() -> new RuntimeException("Prompt not found"));

        String title = promptToDelete.getTitle();
        boolean wasLatest = Boolean.TRUE.equals(promptToDelete.getIsLatest());

        // 2. 删除
        repository.deleteById(id);

        // 3. 如果它是最新版本，则查找旧版本中最“新”的并设置为 isLatest
        if (wasLatest) {
            List<MyPrompt> otherVersions = repository.findByTitle(title);

            if (!otherVersions.isEmpty()) {
                // 找到最新的版本（按日期/ID 排序）
                MyPrompt latest = otherVersions.stream()
                    .max(Comparator.comparing(MyPrompt::getDate)) // 或 getId()
                    .orElseThrow();

                latest.setIsLatest(true);
                repository.save(latest);
            }
        }
    }

    
    public Optional<MyPrompt> getByTitleAndVersion(String title, String version) {
        return repository.findFirstByTitleAndVersion(title, version);
    }

    public Optional<MyPrompt> getLatestByTitle(String title) {
        return repository.findFirstByTitleOrderByDateDesc(title);
    }

    public List<MyPrompt> getAllVersions(String title) {
        return repository.findAllByTitleOrderByDateDesc(title);
    }

    
    public Page<MyPrompt> getPage(Pageable pageable) {
        return repository.findAll(pageable);
    }

    public Page<MyPrompt> searchByTitle(String title, Pageable pageable) {
        return repository.findByTitleContainingIgnoreCase(title, pageable);
    }
    
    public MyPrompt createNewVersion(MyPrompt newPrompt) {
        // 查找已有的同名同作者的 prompt（不含 version，只根据 title）
        List<MyPrompt> existingPrompts = repository.findByTitle(newPrompt.getTitle());

        // 将之前所有的设为非最新版本
        for (MyPrompt prompt : existingPrompts) {
            prompt.setIsLatest(false);
        }
        repository.saveAll(existingPrompts);

        // 设置新版本为最新
        newPrompt.setIsLatest(true);
        newPrompt.setDate(LocalDate.now());

        return repository.save(newPrompt);
    }
    
    public Optional<MyPrompt> getLatestVersion(String title) {
        return repository.findByTitleAndIsLatestTrue(title)
                .stream()
                .findFirst();
    }

    public Optional<MyPrompt> getSpecificVersion(String title, String version) {
        return repository.findFirstByTitleAndVersion(title, version);
    }
}

